package com.vshop.timingtask;

import com.alibaba.fastjson.JSON;
import com.vshop.entity.comentity.PackageCoverPicture;
import com.vshop.entity.comentity.PartnerInfo;
import com.vshop.entity.comentity.PartnerPackage;
import com.vshop.entity.newpojo.TurntoInterfaceUtils;
import com.vshop.entity.newpojo.request.RequestBody.SyncModulePackagesRequestBody;
import com.vshop.entity.newpojo.request.RequestHeader;
import com.vshop.entity.newpojo.request.subRequest.SyncModulePackagesRequest;
import com.vshop.entity.newpojo.response.responseBody.SyncPackagesResponse;
import com.vshop.entity.newpojo.response.subResponse.common._Package;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.entity.requestinterface.syncpackages.request.RequestSyncPackages;
import com.vshop.entity.requestinterface.syncpackages.response.ResponseSyncPackages;
import com.vshop.service.CountryService;
import com.vshop.service.PackageCoverPictureService;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.PartnerPackageService;
import com.vshop.utils.HttpClientTool;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.JaxbUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 北京给深圳内部使用的同步套餐的接口:2.0接口
 *
 * @author lm
 * @date 2019/5/24
 */

@Configuration
@EnableScheduling
@RestController
@Slf4j
public class SyncPackageTask {
    @Value("${xmlIot.BASE_URL}")
    private String BASE_URL;
    @Value("${system.autoTask}")
    private boolean autoTask;

    @Autowired
    PartnerInfoService partnerInfoService;
    @Autowired
    PartnerPackageService packageService;
    @Autowired
    PackageCoverPictureService pictureService;
    @Autowired
    CountryService countryService;

    //@Scheduled(cron = " 0 2 20 * * ?")
    @GetMapping(value = "syncPackage")
    @Async

    public void execute() {
        if (autoTask) {
            syncPackageTask();
        }
    }

    public void syncPackageTask() {

        log.info("每1天晚上20点执行一次的syncPackage开始执行！");

        //1，取数据库取partnerCode出来
        List<PartnerInfo> partnerList = partnerInfoService.findPartnerCode();

        partner:
        for (PartnerInfo partner : partnerList) {

            boolean b1 = StringUtils.isBlank(partner.getPartnerCode()) || StringUtils.isBlank(partner.getSecret()) || StringUtils.isBlank(partner.getPartnerName());
            if (b1) {
                continue partner;
            }

            String partnerCode = partner.getPartnerCode();
            String partnerName = partner.getPartnerName();
            String secret = partner.getSecret();

            //如果企业编码属于以下列表，直接跳出本次循环 2020-07-20拉出来：partnerCode.equals("P000242") ||
            //2020-08-27拉出来：partnerCode.equals("P000590") ||；partnerCode.equals("P000239") ||；partnerCode.equals("P000315") ||

            boolean b2 = partnerCode.equals("P000270") || partnerCode.equals("0") || partnerCode.equals("P000897") || partnerCode.equals("P000258") ||
                    partnerCode.equals("P000007") || partnerCode.equals("P000280") || partnerCode.equals("P000374") ||
                    partnerCode.equals("P000135") || partnerCode.equals("P000294") || partnerCode.equals("P000672") ||
                    partnerCode.equals("P000665") || partnerCode.equals("P000890") || partnerCode.equals("P000373") ||
                    partnerCode.equals("P001051") || partnerCode.equals("P000278") ||
                    partnerCode.equals("P000345") || partnerCode.equals("P000045") || partnerCode.equals("P000920") ||
                    partnerCode.equals("P000042") || partnerCode.equals("P000044") || partnerCode.equals("P000243") ||
                    partnerCode.equals("P000881") || partnerCode.equals("P000172") || partnerCode.equals("P000204") ||
                    partnerCode.equals("P000986") || partnerCode.equals("P000043") || partnerCode.equals("P000039") ||
                    partnerCode.equals("P000158") || partnerCode.equals("P000148") ||
                    partnerCode.equals("P000985") || partnerCode.equals("P000318") || partnerCode.equals("P000319") ||
                    partnerCode.equals("P001043") || partnerCode.equals("P000193") || partnerCode.equals("P000819") ||
                    partnerCode.equals("P000698") || partnerCode.equals("P000848") || partnerCode.equals("P000229") ||
                    partnerCode.equals("P000279") || partnerCode.equals("P000340") ||
                    partnerCode.equals("P000091") || partnerCode.equals("P000127") || partnerCode.equals("P000845") ||
                    partnerCode.equals("P000126") || partnerCode.equals("P000339") || partnerCode.equals("P000093") ||
                    partnerCode.equals("P000046") || partnerCode.equals("P000368") || partnerCode.equals("P000623") ||
                    partnerCode.equals("P000648") || partnerCode.equals("P000316") || partnerCode.equals("P000257") ||
                    partnerCode.equals("P000752") || partnerCode.equals("P000230") || partnerCode.equals("P000611") ||
                    partnerCode.equals("P000758") || partnerCode.equals("P000841") ||
                    partnerCode.equals("P000850") || partnerCode.equals("P000114") || partnerCode.equals("P000697") ||
                    partnerCode.equals("P000094") || partnerCode.equals("P000620") || partnerCode.equals("P000942") ||
                    partnerCode.equals("P000931") || partnerCode.equals("P000324") || partnerCode.equals("P000122") ||
                    partnerCode.equals("P000244") || partnerCode.equals("P000576") || partnerCode.equals("P000958") ||
                    partnerCode.equals("P000292") || partnerCode.equals("P000163") || partnerCode.equals("P000205") ||
                    partnerCode.equals("P000362") || partnerCode.equals("P000557") || partnerCode.equals("P000221") ||
                    partnerCode.equals("P000922") || partnerCode.equals("P000225") || partnerCode.equals("P001032") ||
                    partnerCode.equals("P000882") || partnerCode.equals("P000916") || partnerCode.equals("P002038") ||
                    partnerCode.equals("P002040") || partnerCode.equals("P002098") || partnerCode.equals("P002099") ||
                    partnerCode.equals("P000883") || partnerCode.equals("P000889") || partnerCode.equals("P000984") ||
                    partnerCode.equals("P001053") || partnerCode.equals("P002173") ||

                    partnerCode.equals("P000637") || partnerCode.equals("P000591") || partnerCode.equals("P000983");

            if (b2) {
                log.info("无需请求列表企业");
                continue partner;
            }

            //先去查询一下企业到底有多少条套餐记录
            RequestSyncPackages sync = new RequestSyncPackages();
            sync.setPageNo(1);
            sync.setPageSize(1);
            sync.setPartnerCode(partnerCode);
            sync.setSecret(secret);

            String requestInterface = JSON.toJSONString(sync);

            log.info("【syncPackage】数量请求：" + requestInterface);
            String url = "http://localhost:8085/iot" + Constant.iot_syncPackages;
            // 发送post请求，并接收返回结果
            String returnStr = HttpUtil.httpPost(url, requestInterface);
            log.info("【syncPackage】数量响应：" + returnStr);

            ResponseSyncPackages response = JSON.parseObject(returnStr, ResponseSyncPackages.class);

            if (response != null && response.getPage() != null) {

                int totalCount = response.getPage().getTotalCount();

                if (totalCount > 0) {

                    double total;

                    if (Math.ceil(totalCount / 1000) < 1) {
                        total = 1;
                    } else {
                        total = Math.ceil(totalCount / 1000) + 1;
                    }

                    for (int x = 1; x <= total; x++) {

                        log.info("企业是：" + partnerCode + ";totalCount是：" + totalCount + ";total是：" + total + ";x是：" + x);

                        // 请求参数拼接
                        SyncModulePackagesRequest request = new SyncModulePackagesRequest();
                        TurntoInterfaceUtils utils = new TurntoInterfaceUtils();
                        RequestHeader header = utils.getRequestHeader(Constant.cmd_syncPackages, partnerCode);
                        request.setHeader(header);

                        SyncModulePackagesRequestBody body = new SyncModulePackagesRequestBody();
                        body.setPageNo(Integer.toString(x));
                        body.setPageSize("1000");

                        request.setBody(body);
                        String sign = "";
                        try {
                            sign = utils.getSign(header, body, body.getClass(), secret);
                        } catch (Exception e) {
                            log.info("计算sign异常：" + e);
                            continue;
                        }
                        request.setSign(sign);
                        // 将参数转换成XML格式
                        String sRequest = new JaxbUtil(SyncModulePackagesRequest.class).toXml(request, "utf-8");
                        log.info("【syncPackage】请求：" + sRequest);
                        String result = HttpClientTool.sendHttpPost(BASE_URL, sRequest);
                        log.info("url=" + BASE_URL + ";接口名：" + Constant.cmd_syncPackages);

                        log.info("【syncPackage】响应：" + result);

                        if (!result.equals("-1")) {

                            // 将回传的xml转换成object数据
                            SyncPackagesResponse responseObj = new JaxbUtil(SyncPackagesResponse.class).fromXml(result, "utf-8");

                            if (responseObj != null) {
                                String retCode = responseObj.getHeader().getResultCode();

                                if (Constant.RET_CODE_0000.equalsIgnoreCase(retCode)) {

                                    // 将SyncModulePackagesResponse收到的package遍历出来
                                    List<_Package> packageList = responseObj.getBody().get_package();

                                    if (packageList != null && !packageList.isEmpty()) {

                                        // 普通套餐
                                        for (_Package p : packageList) {

                                            String packageCode = p.getPackageCode();
                                            String coverCountryMcc = p.getCoverCountryMcc();
                                            String coverCountrys = p.getCoverCountrys();
                                            String packageStatus = p.getStatus();

                                            String mccs = "";
                                            String continentName = "";
                                            String continentNameEN = "";
                                            String coverCountrysEN = "";

                                            //将mcc用；截取，然后拿着数据去查询
                                            String[] strs = p.getCoverCountryMcc().split(";");

                                            for (int i = 0; i < strs.length; i++) {

                                                mccs = strs[i];

                                                continentName += countryService.queryContinent(mccs) + ";";
                                                continentNameEN += countryService.queryContinentEN(mccs) + ";";
                                                coverCountrysEN += countryService.queryCountryEN(mccs) + ";";
                                            }
                                            // 最后一个，去掉
                                            if (!"".equals(continentName) || !"".equals(coverCountrys)) {

                                                continentName = continentName.substring(0, continentName.length() - 1);
                                                continentNameEN = continentNameEN.substring(0, continentNameEN.length() - 1);
                                                coverCountrysEN = coverCountrysEN.substring(0, coverCountrysEN.length() - 1);
                                            }

                                            //先查数据库有没有这个订单
                                            int count = packageService.findCountByCondition(packageCode, partnerCode);

                                            if (count <= 0) {

                                                //已分配（可用）
                                                if (packageStatus.equals("2")) {
                                                    PartnerPackage product = new PartnerPackage();
                                                    product.setPartnerCode(partnerCode);
                                                    product.setPartnerName(partnerName);
                                                    product.setPackageCode(p.getPackageCode());
                                                    product.setPackageName(p.getPackageName());
                                                    product.setPackageNameEN(p.getPackageNameEn());
                                                    product.setPackageShortDesc(p.getPackageDesc());
                                                    product.setPackageFlow(p.getPackageFlow());
                                                    product.setPackageType(p.getPackageType());
                                                    product.setBuyType(p.getBuyType());
                                                    product.setPriceType(p.getPriceType());
                                                    product.setMinOrderPeriod(p.getMinOrderPeriod());
                                                    product.setMaxOrderPeriod(p.getMaxOrderPeriod());
                                                    product.setPackageStatus(p.getStatus());
                                                    product.setStatus("0");
                                                    product.setCoverMcc(coverCountryMcc);
                                                    product.setCoverCountrys(coverCountrys);
                                                    product.setCoverCountrysEN(coverCountrysEN);
                                                    product.setContinentName(continentName);
                                                    product.setContinentNameEN(continentNameEN);
                                                    product.setCostPrice(p.getCostPrice());
                                                    product.setPackage_usage_attribute(p.getPackage_usage_attribute());
                                                    packageService.storagePackage(product);
                                                } //已停售（不可用-停售）
                                                else if (packageStatus.equals("3")) {

                                                    PartnerPackage product = new PartnerPackage();
                                                    product.setPartnerCode(partnerCode);
                                                    product.setPartnerName(partnerName);
                                                    product.setPackageCode(p.getPackageCode());
                                                    product.setPackageName(p.getPackageName());
                                                    product.setPackageNameEN(p.getPackageNameEn());
                                                    product.setPackageShortDesc(p.getPackageDesc());
                                                    product.setPackageFlow(p.getPackageFlow());
                                                    product.setPackageType(p.getPackageType());
                                                    product.setBuyType(p.getBuyType());
                                                    product.setPriceType(p.getPriceType());
                                                    product.setMinOrderPeriod(p.getMinOrderPeriod());
                                                    product.setMaxOrderPeriod(p.getMaxOrderPeriod());
                                                    product.setPackageStatus(p.getStatus());
                                                    product.setStatus("4");
                                                    product.setCoverMcc(coverCountryMcc);
                                                    product.setCoverCountrys(coverCountrys);
                                                    product.setCoverCountrysEN(coverCountrysEN);
                                                    product.setContinentName(continentName);
                                                    product.setContinentNameEN(continentNameEN);
                                                    product.setCostPrice(p.getCostPrice());
                                                    product.setPackage_usage_attribute(p.getPackage_usage_attribute());
                                                    packageService.storagePackage(product);


                                                    //如果此时套餐不可用了，还需要去新建的套餐列表里面
                                                }

                                            } else {

                                                //已经有这条数据，我们需要去比对套餐的状态是不是还有效,另外需要去比较一下现在数据库的package_usage_attribute这个值是否有:先去更新一下package_usage_attribute这个值：

                                                PartnerPackage pro = new PartnerPackage();
                                                pro.setPartnerCode(partnerCode);
                                                pro.setPackageCode(packageCode);
                                                pro.setPackage_usage_attribute(p.getPackage_usage_attribute());
                                                packageService.update_package_usage_attribute(pro);

                                                // 第二步：

                                                String statusStr = packageService.queryPackageStatusByCode(packageCode, partnerCode);

                                                //获取到的套餐的状态跟数据库的状态不一样，此时要更新数据库
                                                // 如果之前是2，现在变成3了的话就要更新

                                                if (statusStr.equals("2") && !packageStatus.equalsIgnoreCase(statusStr)) {

                                                    PartnerPackage product = new PartnerPackage();
                                                    product.setPartnerCode(partnerCode);
                                                    product.setPackageCode(packageCode);
                                                    product.setPackageStatus(packageStatus);
                                                    product.setStatus("4");
                                                    packageService.updatePackageStatus(product);

                                                } else {
                                                    continue;
                                                }

                                            }

                                            //图片信息入库
                                            int c = pictureService.findPictureExistOrNot(packageCode, partnerCode);

                                            if (c <= 0) {
                                                PackageCoverPicture picture = new PackageCoverPicture();
                                                picture.setPartnerCode(partnerCode);
                                                picture.setPackageCode(packageCode);
                                                pictureService.storagePicture(picture);
                                            }

                                        }

                                    } else {
                                        continue;
                                    }
                                } else {
                                    continue;
                                }

                            } else {
                                continue;
                            }

                        } else {
                            continue;
                        }

                    }
                } else {
                    continue;
                }
            } else {
                continue;
            }
        }

        log.info("每1天晚上20点执行一次的syncPackage执行完毕！");
    }
}
